from flasgger import swag_from
from flask import current_app, g, render_template, request
from flask.views import MethodView

from app.extensions import json_response
from app.version.models import Version, VersionReachUser
from utils.base import login_require


class Versions(MethodView):
    @swag_from("./apidocs/get_all_versions.yml")
    def get(self):
        """获取demo数据，支持分页查询"""
        query = request.values
        limit = int(query.get("limit", 10))
        offset = int(query.get("offset", 1))
        total, versions_data = Version.get_all_versions(limit, offset)
        return render_template("versions/index.html", versions=versions_data)


class VersionView(MethodView):
    @swag_from("./apidocs/get_single_version.yml")
    def get(self, version_id):
        """获取单个demo数据"""
        # 直接查询数据库也可，封装成函数可以做一些缓存
        demo = Version.get_by_demo_id(version_id)
        return json_response(data=demo.to_dict())

    @swag_from("./apidocs/update_version.yml")
    def put(self, version_id):
        """更新demo"""
        body = request.json
        if not body:
            return json_response(code=400, data={"msg": "没有传入更新的数据"})
        Version.update_by_id(version_id, body)
        return json_response(code=200)

    @swag_from("./apidocs/delete_version.yml")
    def delete(self, version_id):
        """删除demo"""
        Version.delete_by_id(version_id)

        current_app.logger.info(f"删除{version_id}完成")

        # 接口返回值可以只有状态码，200表示操作成功 404表示找不到对象 400表示错误
        return json_response(code=200)


class VersionCreate(MethodView):
    @swag_from("./apidocs/add_version.yml")
    def post(self):
        """保存demo数据"""
        body = request.json
        res = Version.create(**body)

        # 返回json格式的数据，数据必须可以json序列化
        # to_dict 方法可以将对象转成字典
        return json_response(data=res.to_dict())


class VersionLatest(MethodView):
    @login_require
    @swag_from("./apidocs/get_latest_version.yml")
    def get(self):
        USER_REACH = 1
        USER_NOT_REACH = 0

        latest = Version.select().order_by(Version.id.desc()).first()
        if not latest:
            return json_response(code=200, data={})

        data = latest.to_dict()
        reach_user = VersionReachUser.filter(
            user_id=g.user_id, version_id=latest.id
        ).first()
        if reach_user:
            data["status"] = USER_REACH
        else:
            data["status"] = USER_NOT_REACH
        return json_response(data=data)


class VersionReach(MethodView):
    @login_require
    @swag_from("./apidocs/post_latest_version.yml")
    def post(self, version_id):
        VersionReachUser.create(version_id=version_id, user_id=g.user_id)
        return json_response(code=200)
